<template>
  <view class="profile-page">
    <!-- 未登录状态 -->
    <view v-if="!isLoggedIn" class="login-prompt">
      <view class="login-content">
        <image class="default-avatar" src="https://via.placeholder.com/120x120/ff6b35/ffffff?text=用户" mode="aspectFill" />
        <text class="login-title">登录后享受更多功能</text>
        <button class="login-btn" @click="goToLogin">立即登录</button>
        <button class="debug-btn" @click="debugCheckStatus">调试：检查状态</button>
      </view>
    </view>

    <!-- 已登录状态 -->
    <view v-else>
    <!-- 用户信息头部 -->
    <view class="profile-header">
      <view class="user-info">
          <image class="avatar" :src="userInfo.avatar || '/static/icons/course-default.png'" mode="aspectFill" />
        <view class="user-details">
          <text class="username">{{ userInfo.name }}</text>
          <text class="user-level">{{ userInfo.level }}</text>
        </view>
        <view class="edit-btn" @click="editProfile">
          编辑
        </view>
      </view>
      
      <!-- 统计信息 -->
      <view class="stats-row">
        <view class="stat-item" v-for="stat in userStats" :key="stat.label">
          <text class="stat-number">{{ stat.value }}</text>
          <text class="stat-label">{{ stat.label }}</text>
        </view>
      </view>
    </view>

    <!-- 功能菜单 -->
    <view class="menu-section">
      <view class="menu-title">我的服务</view>
      <view class="menu-grid">
        <view 
          v-for="menu in menuItems" 
          :key="menu.name"
          class="menu-item"
          @click="handleMenuClick(menu.action)"
        >
          <text class="menu-icon">{{ menu.icon }}</text>
          <text class="menu-name">{{ menu.name }}</text>
          <view class="menu-badge" v-if="menu.badge">{{ menu.badge }}</view>
        </view>
      </view>
    </view>

    <!-- 我的订单 -->
    <view class="order-section">
      <view class="section-header">
        <text class="section-title">我的订单</text>
        <text class="view-all" @click="viewAllOrders">查看全部 ></text>
      </view>
      <view class="order-types">
        <view 
          v-for="type in orderTypes" 
          :key="type.name"
          class="order-type"
          @click="viewOrders(type.status)"
        >
          <text class="order-icon">{{ type.icon }}</text>
          <text class="order-name">{{ type.name }}</text>
          <view class="order-badge" v-if="type.count > 0">{{ type.count }}</view>
        </view>
      </view>
    </view>

    <!-- 其他功能 -->
    <view class="other-section">
      <profile-menu-item 
        v-for="item in otherMenus" 
        :key="item.name"
        :item="item"
        @click="handleOtherMenuClick(item.action)"
      />
    </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import ProfileMenuItem from '../../components/ProfileMenuItem.vue'
import { userAPI } from '../../utils/api.js'
import authManager from '../../utils/auth.js'

// 登录状态
const isLoggedIn = ref(false)
const userInfo = ref({
  name: '学习达人',
  level: 'VIP会员',
  avatar: ''
})

// 检查登录状态
const checkLoginStatus = async () => {
  console.log('=== 开始检查登录状态 ===')
  
  // 直接检查存储的数据
  const token = uni.getStorageSync('accessToken')
  const userId = uni.getStorageSync('userId')
  console.log('直接检查存储 - token:', token, 'userId:', userId)
  
  const isLoggedInStatus = authManager.isLoggedIn()
  console.log('AuthManager登录状态:', isLoggedInStatus)
  
  if (isLoggedInStatus) {
    console.log('用户已登录，更新界面状态')
    isLoggedIn.value = true
    const userInfoData = authManager.getUserInfo()
    console.log('用户信息:', userInfoData)
    
    // 先设置默认值
    userInfo.value = {
      name: '用户',
      level: '未设置邮箱',
      avatar: '/static/icons/course-default.png'
    }
    
    // 异步获取用户详细信息
    await loadUserDetailInfo()
    
    // 获取用户数据
    loadUserData()
  } else {
    console.log('用户未登录，显示登录界面')
    isLoggedIn.value = false
  }
  
  console.log('=== 登录状态检查完成，isLoggedIn.value =', isLoggedIn.value, '===')
}

// 获取用户详细信息 - 使用getUser方法获取完整信息
const loadUserDetailInfo = async () => {
  try {
    // 先尝试调用getUser接口获取完整用户信息
    const result = await userAPI.getUserInfo()
    console.log('getUser接口返回结果:', result)
    
    if (result.code === '00000' && result.data) {
      const userData = result.data
      console.log('从getUser获取的用户数据:', userData)
      
      userInfo.value = {
        name: userData.nickname || userData.username || '用户',
        level: userData.email || '未设置邮箱',
        avatar: getMinioFileUrl(userData.filePath) || '/static/icons/course-default.png'
      }
    } else {
      // 如果getUser失败，使用登录时获取的信息作为备用
      const userInfoData = authManager.getUserInfo()
      console.log('使用AuthManager备用信息:', userInfoData)
      
      if (userInfoData) {
        userInfo.value = {
          name: userInfoData.nickname || userInfoData.username || '用户',
          level: userInfoData.email || '未设置邮箱',
          avatar: getMinioFileUrl(userInfoData.filePath) || userInfoData.avatar || '/static/icons/course-default.png'
        }
      } else {
        // 如果都没有，使用默认值
        userInfo.value = {
          name: '用户',
          level: '未设置邮箱',
          avatar: '/static/icons/course-default.png'
        }
      }
    }
  } catch (error) {
    console.error('获取用户详细信息失败:', error)
    // 使用登录时的信息作为备用
    const userInfoData = authManager.getUserInfo()
    if (userInfoData) {
      userInfo.value = {
        name: userInfoData.nickname || userInfoData.username || '用户',
        level: userInfoData.email || '未设置邮箱',
        avatar: getMinioFileUrl(userInfoData.filePath) || userInfoData.avatar || '/static/icons/course-default.png'
      }
    } else {
      userInfo.value = {
        name: '用户',
        level: '未设置邮箱',
        avatar: '/static/icons/course-default.png'
      }
    }
  }
  console.log('最终设置的用户信息:', userInfo.value)
}

// 处理MinIO文件URL的函数（参考learn-fronted的实现）
const getMinioFileUrl = (filePath) => {
  if (!filePath) {
    return ''
  }
  
  // 如果已经是完整的URL，直接返回
  if (filePath.startsWith('http://') || filePath.startsWith('https://')) {
    return filePath
  }
  
  // 如果是相对路径，拼接MinIO基础URL
  const minioUrl = 'http://172.172.2.99:9000' // 根据您的后端配置调整
  return `${minioUrl}${filePath}`
}

// 加载用户数据 - 从后端API获取真实数据
const loadUserData = async () => {
  try {
    console.log('开始加载用户真实数据...')
    
    // 获取用户统计信息
    const statsResult = await userAPI.getStats()
    if (statsResult.code === '00000' && statsResult.data) {
      userStats.value = [
        { label: '关注', value: statsResult.data.following || 0 },
        { label: '粉丝', value: statsResult.data.followers || 0 },
        { label: '作品', value: statsResult.data.works || 0 },
        { label: '积分', value: statsResult.data.points || 0 }
      ]
    }
    
    // 获取订单统计
    const orderResult = await userAPI.getOrderStats()
    if (orderResult.code === '00000' && orderResult.data) {
      orderTypes.value = [
        { icon: '📦', name: '待付款', status: 'unpaid', count: orderResult.data.unpaid || 0 },
        { icon: '🚚', name: '待发货', status: 'unshipped', count: orderResult.data.unshipped || 0 },
        { icon: '📋', name: '待收货', status: 'unreceived', count: orderResult.data.unreceived || 0 },
        { icon: '⭐', name: '待评价', status: 'unrated', count: orderResult.data.unrated || 0 }
      ]
    }
    
    console.log('加载用户数据完成')
  } catch (error) {
    console.error('加载用户数据失败:', error)
    // 如果API调用失败，使用默认值
    userStats.value = [
      { label: '关注', value: 0 },
      { label: '粉丝', value: 0 },
      { label: '作品', value: 0 },
      { label: '积分', value: 0 }
    ]
    
    orderTypes.value = [
      { icon: '📦', name: '待付款', status: 'unpaid', count: 0 },
      { icon: '🚚', name: '待发货', status: 'unshipped', count: 0 },
      { icon: '📋', name: '待收货', status: 'unreceived', count: 0 },
      { icon: '⭐', name: '待评价', status: 'unrated', count: 0 }
    ]
  }
}

// 跳转到登录页面
const goToLogin = () => {
  uni.navigateTo({
    url: '/pages/LoginPage/LoginPage'
  })
}

// 调试：手动检查状态
const debugCheckStatus = () => {
  console.log('=== 手动调试检查状态 ===')
  checkLoginStatus()
  
  // 显示当前存储的数据
  const token = uni.getStorageSync('accessToken')
  const userId = uni.getStorageSync('userId')
  const userInfo = uni.getStorageSync('userInfo')
  const authManagerUserInfo = authManager.getUserInfo()
  
  console.log('当前存储数据:')
  console.log('- token:', token)
  console.log('- userId:', userId)
  console.log('- userInfo:', userInfo)
  console.log('- authManager.getUserInfo():', authManagerUserInfo)
  
  const userInfoStr = authManagerUserInfo ? JSON.stringify(authManagerUserInfo, null, 2) : 'null'
  
  uni.showModal({
    title: '调试信息',
    content: `Token: ${token ? '已保存' : '未保存'}\nUserId: ${userId || '未保存'}\n登录状态: ${isLoggedIn.value ? '已登录' : '未登录'}\n\n用户信息:\n${userInfoStr}`,
    showCancel: false
  })
}

// 退出登录
const logout = () => {
  uni.showModal({
    title: '提示',
    content: '确定要退出登录吗？',
    success: (res) => {
      if (res.confirm) {
        // 使用认证管理器清除登录信息
        authManager.clearLoginInfo()
        
        // 更新状态
        isLoggedIn.value = false
        
        uni.showToast({
          title: '已退出登录',
          icon: 'success'
        })
      }
    }
  })
}

const userStats = ref([
  { label: '关注', value: 0 },
  { label: '粉丝', value: 0 },
  { label: '作品', value: 0 },
  { label: '积分', value: 0 }
])

const menuItems = [
  { icon: '❤️', name: '我的收藏', action: 'favorites', badge: 12 },
  { icon: '🎬', name: '我的作品', action: 'works', badge: 5 },
  { icon: '🎟️', name: '优惠券', action: 'coupons', badge: 3 },
  { icon: '💰', name: '我的钱包', action: 'wallet' },
  { icon: '🎁', name: '积分商城', action: 'points' },
  { icon: '📞', name: '客服', action: 'service' }
]

const orderTypes = ref([
  { icon: '📦', name: '待付款', status: 'unpaid', count: 0 },
  { icon: '🚚', name: '待发货', status: 'unshipped', count: 0 },
  { icon: '📋', name: '待收货', status: 'unreceived', count: 0 },
  { icon: '⭐', name: '待评价', status: 'unrated', count: 0 }
])

const otherMenus = [
  { icon: '⚙️', name: '设置', action: 'settings' },
  { icon: '📱', name: '关于我们', action: 'about' },
  { icon: '🆘', name: '帮助中心', action: 'help' },
  { icon: '🚪', name: '退出登录', action: 'logout' }
]

const editProfile = () => {
  if (!isLoggedIn.value) {
    uni.showToast({ title: '请先登录', icon: 'none' })
    return
  }
  
  uni.navigateTo({
    url: '/pages/EditProfilePage/EditProfilePage'
  })
}

const handleMenuClick = (action) => {
  switch (action) {
    case 'favorites':
      uni.navigateTo({ url: '/pages/FavoritesPage/FavoritesPage' })
      break
    case 'coupons':
      uni.navigateTo({ url: '/pages/CouponsPage/CouponsPage' })
      break
    default:
      uni.showToast({ title: `${action}功能开发中`, icon: 'none' })
  }
}

const viewAllOrders = () => {
  uni.showToast({ title: '查看全部订单', icon: 'none' })
}

const viewOrders = (status) => {
  uni.showToast({ title: `查看${status}订单`, icon: 'none' })
}

const handleOtherMenuClick = (action) => {
  switch (action) {
    case 'logout':
      logout()
      break
    default:
  uni.showToast({ title: `${action}功能开发中`, icon: 'none' })
}
}

// 页面显示时检查登录状态
onMounted(() => {
  console.log('ProfilePage onMounted')
  checkLoginStatus()
  
  // 监听登录状态变化事件
  uni.$on('loginStatusChanged', () => {
    console.log('收到登录状态变化事件')
    checkLoginStatus()
  })
})

// 使用uniapp的页面生命周期钩子
defineExpose({
  onShow() {
    console.log('ProfilePage onShow')
    checkLoginStatus()
  },
  
  // 页面卸载时移除事件监听
  onUnload() {
    uni.$off('loginStatusChanged')
  }
})
</script>

<style scoped>
.profile-page {
  background: #f5f5f5;
  min-height: 100vh;
}

.login-prompt {
  background: linear-gradient(135deg, #ff6b35, #ff8c42);
  padding: 80rpx 40rpx;
  text-align: center;
  color: #fff;
}

.login-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.default-avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  margin-bottom: 30rpx;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
}

.login-title {
  font-size: 32rpx;
  margin-bottom: 40rpx;
  opacity: 0.9;
}

.login-btn {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
  border: 2rpx solid rgba(255, 255, 255, 0.3);
  border-radius: 40rpx;
  padding: 20rpx 60rpx;
  font-size: 28rpx;
  margin-bottom: 20rpx;
}

.debug-btn {
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
  border: 2rpx solid rgba(255, 255, 255, 0.2);
  border-radius: 30rpx;
  padding: 15rpx 40rpx;
  font-size: 24rpx;
  opacity: 0.8;
}
.profile-header {
  background: linear-gradient(135deg, #ff6b35, #ff8c42);
  padding: 40rpx 30rpx;
  color: #fff;
}
.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
}
.avatar {
  width: 120rpx;
  height: 120rpx;
  border-radius: 60rpx;
  margin-right: 30rpx;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
}
.user-details {
  flex: 1;
}
.username {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
  display: block;
}
.user-level {
  font-size: 24rpx;
  opacity: 0.9;
}
.edit-btn {
  padding: 15rpx 30rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 30rpx;
  font-size: 24rpx;
}
.stats-row {
  display: flex;
  justify-content: space-around;
}
.stat-item {
  text-align: center;
}
.stat-number {
  font-size: 32rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
}
.stat-label {
  font-size: 22rpx;
  opacity: 0.9;
}
.menu-section {
  background: #fff;
  margin: 20rpx;
  border-radius: 20rpx;
  padding: 30rpx;
}
.menu-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 30rpx;
  color: #333;
}
.menu-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 30rpx;
}
.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}
.menu-icon {
  font-size: 60rpx;
  margin-bottom: 15rpx;
}
.menu-name {
  font-size: 24rpx;
  color: #666;
}
.menu-badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  background: #ff4757;
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 20rpx;
  min-width: 30rpx;
  text-align: center;
}
.order-section {
  background: #fff;
  margin: 20rpx;
  border-radius: 20rpx;
  padding: 30rpx;
}
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
}
.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}
.view-all {
  font-size: 24rpx;
  color: #999;
}
.order-types {
  display: flex;
  justify-content: space-around;
}
.order-type {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}
.order-icon {
  font-size: 50rpx;
  margin-bottom: 15rpx;
}
.order-name {
  font-size: 22rpx;
  color: #666;
}
.order-badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  background: #ff4757;
  color: #fff;
  font-size: 20rpx;
  padding: 4rpx 8rpx;
  border-radius: 20rpx;
  min-width: 30rpx;
  text-align: center;
}
.other-section {
  margin: 20rpx;
}
</style>
